<?php
namespace app\models\custom;

use app\models\User;
use yii;
use yii\web\IdentityInterface;
use yii\web\UnauthorizedHttpException;

class Identity implements IdentityInterface {
    /** @var User */
    public $user;
    public $role;

    public function __construct(User $user) {
        $this->user = $user;
        $this->role = $user->role;
    }

    /**
     * 根据给到的ID查询身份。
     *
     * @param string|integer $id 被查询的ID
     * @return IdentityInterface|null 通过ID匹配到的身份对象
     */
    public static function findIdentity($id) {
        $model = User::findOne($id);
        return $model ? new static($model) : null;
    }

    // 根据 token 查询身份
    public static function findIdentityByAccessToken($token, $type = null) {
        return null;
    }

    /**
     * @return int|string 当前用户ID
     */
    public function getId() {
        return $this->user-> id;
    }

    /**
     * @return string 当前用户的（cookie）认证密钥
     */
    public function getAuthKey() {
        return sha1($this->user->password . Yii::$app->params['cookieAuthkey'] . $this->user->id);
    }

    /**
     * @param string $authKey
     * @return boolean if auth key is valid for current user
     */
    public function validateAuthKey($authKey) {
        return $this->getAuthKey() === $authKey;
    }
}